package mk.jug.academy.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import mk.jug.academy.model.Event;
import mk.jug.academy.model.Page;

import org.springframework.stereotype.Repository;


/**
 * DAO for the {@link Event} entity.
 *
 * @author Ice.Penov
 */
@Repository
public class EventDAO extends GenericDAO<Event> {
	
	/**
	 * Finds the latest events limited by the given boundaries.
	 */
	public Page<Event> findLatest(final int start, final int end) {
		return new QueryEMContext<Page<Event>>() {
			@Override @SuppressWarnings("unchecked")
			public Page<Event> query(EntityManager em) {
				Query query = em.createQuery("Select evt from mk.jug.academy.model.Event evt order by evt.modified desc");
				query.setFirstResult(start);
				query.setMaxResults(end);
				List<Event> list = query.getResultList();
				query = em.createQuery("Select count(evt.id) from mk.jug.academy.model.Event evt");
				return new Page<Event>(initialize(list), (Integer) query.getSingleResult());
			}
		}.result();
	}
	
	/**
	 * Hard-deletes the event.
	 */
	public void delete(final Event event) {
		new UpdateEMContext() {
			public void update(EntityManager em) {
				Query query = em.createQuery("Delete from mk.jug.academy.model.Event evt where evt.id = :id");
				query.setParameter("id", event.getId());
				query.executeUpdate();
			}
		};
	}

}